package com.cecil.generate.mapper;

import com.cecil.generate.domain.Column;
import com.cecil.generate.domain.Table;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;

@Mapper
public interface DatabaseMapper {

    @Select("show full columns from `${dbName}`.${tableName}")
    List<Column> findColumn(@Param("dbName") String dbName, @Param("tableName") String tableName);

    @Select("select a.* from information_schema.`TABLES` a where a.TABLE_SCHEMA = '${dbName}' AND a.TABLE_NAME = #{tableName}")
    Table findTable(@Param("dbName") String dbName, @Param("tableName") String tableName);

    @Select("select a.* from information_schema.`TABLES` a where a.TABLE_SCHEMA = '${dbName}'")
    List<Table> findTableList(@Param("dbName") String dbName);

    @SelectProvider(value = Provider.class, method = "findByDbNameTableNames")
    List<Table> findByDbNameTableNames(@Param("dbName") String dbName, @Param("tableNames") List<String> tableNames);

    class Provider {

        public String findByDbNameTableNames(String dbName, List<String> tableNames) {
            SQL sql = new SQL();
            sql.SELECT("a.*").FROM("information_schema.`TABLES` a")
                    .WHERE("a.TABLE_SCHEMA = '${dbName}'");
            if (null != tableNames && !tableNames.isEmpty()) {
                StringBuilder tables = new StringBuilder();
                for (String tableName : tableNames) {
                    tables.append("\"").append(tableName).append("\"").append(",");
                }
                sql.WHERE("a.table_name IN (" + tables.substring(0, tables.length() - 1) + ")");
            }
            return sql.toString();
        }
    }

}
